package com.dtguai.web.web.sys.controller.admin;


import com.github.pagehelper.PageInfo;
import com.dtguai.web.base.action.BaseAction;
import com.dtguai.web.common.annotation.SysLog;
import com.dtguai.web.common.error.ErrorCode;
import com.dtguai.web.common.validator.BaseAssert;
import com.dtguai.web.common.validator.ValidatorUtils;
import com.dtguai.web.common.validator.group.AddGroup;
import com.dtguai.web.common.validator.group.UpdateGroup;
import com.dtguai.web.web.sys.model.SysDefAdmin;
import com.dtguai.web.protocol.response.ApiResponse;
import com.dtguai.web.util.constant.Constant;
import com.dtguai.web.web.sys.form.PasswordForm;
import com.dtguai.web.web.sys.form.admin.ListAdminForm;
import com.dtguai.web.web.sys.form.admin.SaveAdminForm;
import com.dtguai.web.web.sys.service.SysDefAdminRoleService;
import com.dtguai.web.web.sys.service.SysDefAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponses;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author guoLiang
 * @date 2018-12-11 02:43:01
 */
@RestController
@RequestMapping("/web/sys/controller/admin")
@Api(value = "web-系统用户接口", tags = {"web-系统用户接口"})
public class SysDefAdminApi extends BaseAction {

    @Autowired
    private SysDefAdminService sysDefAdminService;

    @Autowired
    private SysDefAdminRoleService sysDefAdminRoleService;


    /**
     * 所有用户列表
     */
    @ApiOperation(value = "分页查询管理员列表-返回PageInfo", notes = "返回数据和分页信息")
    @GetMapping(value = "/list", produces = "application/json;charset=UTF-8")
    @RequiresPermissions("sys:user:list")
    public ResponseEntity<ApiResponse<PageInfo<SysDefAdmin>>> getSysDefAdminPage(ListAdminForm sysDefAdmin) {
        //只有超级管理员，才能查看所有管理员列表
        if (getAdminId() != Constant.SUPER_ADMIN) {
            sysDefAdmin.setCreateAdminId(getAdminId());
        }
        List<SysDefAdmin> sysDefAdminList = sysDefAdminService.selectByPage(sysDefAdmin, true, SysDefAdmin.class);
        return ResponseEntity.ok(new ApiResponse<PageInfo<SysDefAdmin>>(new PageInfo<SysDefAdmin>(sysDefAdminList)));
    }

    /**
     * 获取登录的用户信息
     */
    @ApiOperation(value = "获取登录的用户信息", notes = "获取登录的用户信息")
    @GetMapping("/info")
    public ResponseEntity<ApiResponse<SysDefAdmin>> info() {
        return ResponseEntity.ok(new ApiResponse<SysDefAdmin>(getAdmin()));
    }

    /**
     * 修改登录用户密码
     */
    @SuppressWarnings("rawtypes")
    @ApiOperation(value = "修改登录用户密码", notes = "修改登录用户密码")
    @SysLog("修改密码")
    @PostMapping("/password")
    public ResponseEntity<ApiResponse> password(@RequestBody PasswordForm form) {
        // 表单校验
        ValidatorUtils.validateEntity(form);
        //sha256加密
        String password = new Sha256Hash(form.getPassword(), getAdmin().getCode()).toHex();
        //sha256加密
        String newPassword = new Sha256Hash(form.getNewPassword(), getAdmin().getCode()).toHex();
        //更新密码
        boolean flag = sysDefAdminService.updatePassword(getAdminId(), password, newPassword);
        if (!flag) {
            return ResponseEntity.ok(new ApiResponse(ErrorCode.USER_OLD_PASSWORD_ERROR));
        }
        return ResponseEntity.ok(new ApiResponse());
    }

    /**
     * 用户信息
     */
    @ApiOperation(value = "根据主键查询用户信息", notes = "根据主键查询用户信息")
    @GetMapping("/infoByKey")
    @RequiresPermissions("sys:user:info")
    @ApiImplicitParam(name = "id", value = "主键id", required = true, example = "")
    @ApiResponses({
            @io.swagger.annotations.ApiResponse(code = 1022, message = "id不能为空")
    })
    public ResponseEntity<ApiResponse<SysDefAdmin>> getSysDefAdminByKey(Integer id) {
        BaseAssert.isNull(id, ErrorCode.ID_NOT_NULL);
        SysDefAdmin sysDefAdmin = sysDefAdminService.selectByKey(id);
        //获取用户所属的角色列表
        List<Integer> roleIdList = sysDefAdminRoleService.getRoleIdList(id);
        sysDefAdmin.setRoleIdList(roleIdList);
        return ResponseEntity.ok(new ApiResponse<SysDefAdmin>(sysDefAdmin));
    }


    /**
     * 保存用户
     */
    @SysLog("添加用户")
    @ApiOperation(value = "添加用户", notes = "添加用户")
    @PostMapping(value = "/save", produces = "application/json;charset=UTF-8")
    @RequiresPermissions("sys:user:save")
    public ResponseEntity<ApiResponse<Integer>> sysDefAdminSave(@RequestBody SaveAdminForm sysDefAdmin) {
        // 表单校验
        ValidatorUtils.validateEntity(sysDefAdmin, AddGroup.class);
        SysDefAdmin sysDefAdminAdd = new ModelMapper().map(sysDefAdmin, SysDefAdmin.class);
        sysDefAdminAdd.setCreateAdminId(getAdminId());
        Integer id = sysDefAdminService.add(sysDefAdminAdd);
        return ResponseEntity.ok(new ApiResponse<Integer>(id));
    }

    /**
     * 修改用户
     */
    @SysLog("修改用户")
    @ApiOperation(value = "修改用户", notes = "修改用户")
    @PostMapping(value = "/update", produces = "application/json;charset=UTF-8")
    @RequiresPermissions("sys:user:update")
    public ResponseEntity<ApiResponse<Integer>> update(@RequestBody SaveAdminForm sysDefAdmin) {
        // 表单校验
        ValidatorUtils.validateEntity(sysDefAdmin, UpdateGroup.class);
        SysDefAdmin admin = new ModelMapper().map(sysDefAdmin, SysDefAdmin.class)
                .setCode(sysDefAdminService.selectByKey(sysDefAdmin.getId()).getCode());
        sysDefAdminService.update(admin);
        return ResponseEntity.ok(new ApiResponse<Integer>(getAdminId()));
    }

    /**
     * 删除用户
     */
    @SysLog("删除用户")
    @ApiOperation(value = "删除用户", notes = "删除用户")
    @PostMapping("/delete")
    @RequiresPermissions("sys:user:delete")
    @ApiImplicitParam(name = "ids", value = "主键id", required = true, example = "1,2,3,4,5")
    public ResponseEntity<ApiResponse> delete(@RequestBody List<Integer> ids) {
        if (ids.contains(1)) {
            return ResponseEntity.ok(new ApiResponse(ErrorCode.ADMIN_NOT_DELETE));
        }

        if (ids.contains(getAdminId())) {
            return ResponseEntity.ok(new ApiResponse(ErrorCode.NOT_DELETE));
        }

        sysDefAdminService.deleteBatchById(ids);

        return ResponseEntity.ok(new ApiResponse());
    }


}